package collection_;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
 * @author DCSGO
 * @version 1.0
 * CollectionIterator
 * 集合的迭代器
 * 用于遍历集合中的所有元素
 */
public class CollectionIterator {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {
        Collection col = new ArrayList();
        col.add(new Book("三国", "罗贯中", 14.5));
        col.add(new Book("水浒", "施耐庵", 91.4));
        col.add(new Book("红楼", "曹雪芹", 88.8));

        System.out.println(col);
        //[Book{name='三国', author='罗贯中', price=14.5}, Book{name='水浒', author='施耐庵', price=91.4}, Book{name='红楼', author='曹雪芹', price=88.8}]

        Iterator iterator = col.iterator();
        //在通过 Iterator 遍历集合中的元素时 谨记: 判断是否有下一个元素
        while (iterator.hasNext()) {
            Object obj = iterator.next();
            System.out.println(obj);//多态 编译类型为 Object 运行时调用 Book 的 toString
        }
        //Book{name='三国', author='罗贯中', price=14.5}
        //Book{name='水浒', author='施耐庵', price=91.4}
        //Book{name='红楼', author='曹雪芹', price=88.8}

        //iterator.next();
        //抛出 NoSuchElementException 没有有效元素异常

        System.out.println("-----");
        iterator = col.iterator();//当完成遍历后需将迭代器重置
        while (iterator.hasNext()) {//可通过快捷键 itit 快速生成遍历集合的代码
            Object next = iterator.next();
            System.out.println(next);
        }
        //Book{name='三国', author='罗贯中', price=14.5}
        //Book{name='水浒', author='施耐庵', price=91.4}
        //Book{name='红楼', author='曹雪芹', price=88.8}

        System.out.println("-------");
        //当然 遍历也可以用 foreach 底层实现就是用的迭代器
        for (Object obj : col) {
            System.out.println(obj);
        }
        //Book{name='三国', author='罗贯中', price=14.5}
        //Book{name='水浒', author='施耐庵', price=91.4}
        //Book{name='红楼', author='曹雪芹', price=88.8}
    }
}

class Book {
    String name;
    String author;
    double price;

    Book(String name, String author, double price) {
        this.name = name;
        this.author = author;
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                '}';
    }
}
